/**
 *	SkipList:
 *	{
 *		values: Array of {
 *			value: int
 *			skip: int
 *		}
 *		step: int
 *	}
 */
var SkipList = function(array){
	var step;
	var values = [];
	
	var init = function(array){
		array.sort(function(A, B){
			if(A < B) return -1;
			return 1;
		});
	
		step = Math.floor(Math.sqrt(array.length));
		step = (step <= 0)? 1 : step;
		for(var i = 0, j = 0; i < array.length; i++, j++){
			j = j%step;
			
			if(j == 0 && i+step < array.length){
				values.push({
					value: array[i],
					skip: array[i+step],
				});
			} else {
				values.push({
					value: array[i],
				});
			}
			
		}
		
		//alert(step);
		//alert(JSON.stringify(values, null, "\t"));
	};
	
	this.getStep = function(){
		return step;
	};
	
	this.getValues = function(){
		return values;
	};
	
	this.and = function(skipList){
		var valuesB = skipList.getValues();
		var stepB = skipList.getStep();
		
		var arr = [];
	
		for(var i = 0, j = 0; i < values.length && j < valuesB.length;){
			var A = values[i].value;
			var B = valuesB[j].value;
			console.log("A:" + A + " B:" + B + " i:" + i + " j:" + j);
			if(A == B){
				console.log("Equal");
				arr.push(A);
				i++;
				j++;
			} else if(A < B){
				console.log("A < B");
				if(values[i].skip && values[i].skip <= B){
					i += step;
				} else {
					i++;
				}
				console.log("i:" + i);
			} else if(B < A){
				console.log("B < A");
				if(valuesB[i].skip && valuesB[i].skip <= A){
					j += stepB;
				} else {
					j++;
				}
				console.log("j:" + j);
			}
		}
		
		return new SkipList(arr);
	};
	
	this.or = function(skipList){
		var valuesB = skipList.getValues();
		
		var obj = {};
		
		for(var i in values){
			obj[values[i].value] = values[i].value;
		}
		for(var i in valuesB){
			obj[valuesB[i].value] = valuesB[i].value;
		}
		
		var arr = Object.keys(obj);
		
		return new SkipList(arr);
	};
	
	init(array);
};